import React, { Component, useEffect, useState } from 'react';
import { UdPage, UdPageHeader, udConfigProvider, UdForm, IUdFormItem, validators, uaaApp } from '@/lib';
import { Select, Input, Button, Form, message, Upload, Icon, TreeSelect, Spin, BackTop, Affix, Cascader } from 'antd';
import { http } from '@/lib/core/http';
import { UdModal, UdModalForm } from '@/lib/ui/UdModal';
import apis from '@/apis/AnnouncementManage';
import './style.scss';
// 引入编辑器组件
import BraftEditor from 'braft-editor';
// 引入编辑器样式
import 'braft-editor/dist/index.css';
import ossHttp from '@/utils/oss';
import classNames from 'classnames';
import { RouteComponentProps } from 'react-router-dom';
import ButtonGroup from 'antd/lib/button/button-group';
import { UdRadioGroup } from '@/components/UdFormControls';
import _ from 'lodash';
import { ContentUtils } from 'braft-utils';
import { deepLoopFormateTree, findTreeNodeInfo } from '@/utils/methods';
import EditorComponent from '../BraftEditor';
import dayjs from 'dayjs';
import ViewDetailContent from '../ViewDetailModalContent';
import UdSelect from '@/components/UdFormControls/UdSelect'
import udMainStore from '@/store/UdMain'

//接口字段映射
const fieldMap = {
  //品牌公司
  brandCode: 'brandCode',
  //标题
  title: 'title',
  //封面图片
  coverImg: 'coverImg',
  //正文
  content: 'text',
  //附件
  annex: 'enclosure',
  //公告分类
  classification: 'noticeClassId',
  //新增公告分类名称
  addClassificationName: 'noticeClassName',
  //发送对象维度类型
  sendType: 'type',
  //发送对象
  sendTo: 'userIds',
  //分类值
  classificationValue: 'id',
  //分类名称
  classificationName: 'noticeClassName',
};

const CONTENT_MAX_LENGTH = 2000;

const { realname: sendAnnounceName } = JSON.parse(sessionStorage.getItem('UaaSysInfo'))?.profile || {};

class AddNew extends Component<IUpdateAnnouncementProps, IUpdateAnnouncementState> {
  private brandList = udMainStore.brandList
  static defaultState: IUpdateAnnouncementState = {
    brandCode: udMainStore.brandList[0]["brandCode"],
    title: '',
    querying: false,
    //创建一个空的editorState作为初始值
    editorState: BraftEditor.createEditorState(null),
    // editorState: BraftEditor.createEditorState('<p style="text-indent:2em;" size="0" _root="undefined" __ownerID="undefined" __hash="undefined" __altered="false"><strong><em><span style="text-decoration:line-through">122</span></em></strong></p><p style="text-indent:2em;" size="0" _root="undefined" __ownerID="undefined" __hash="undefined" __altered="false"></p><div class="media-wrap image-wrap"><img class="media-wrap image-wrap" alt="语雀" src="https://gw.alipayobjects.com/zos/rmsportal/XuVpGqBFxXplzvLjJBZB.svg"/></div><p></p>'),
    //附件
    annexFile: null,
    //公告分类项
    options: [],
    //发送对象项
    sendOptions: [],
    sendType: 0,
    detailData: { [fieldMap.sendType]: 0 },
    sendToval: [],
  };

  protected pageContainer = udConfigProvider.ui.getPageContainer();
  private form;
  protected handleBtnAuth;

  componentWillMount(otherState?) {
    let state: IUpdateAnnouncementState = _.defaultsDeep({}, this.state, otherState, AddNew.defaultState);
    this.setState(state);
  }

  componentDidMount() {
    // this.getAllClassificationList();
  }

  render() {
    const { title, subTitle, querying, detailData } = this.state;
    const values = detailData;
    let footer = (
      <div className="detail-footer">
        <ButtonGroup>
          {uaaApp.canUse(this.handleBtnAuth) && (
            <>
              <Button
                type="primary"
                onClick={(e) => {
                  this.handleSend(1);
                }}>
                发送
              </Button>
              <Button
                type="primary"
                onClick={(e) => {
                  this.handleSend(0);
                }}>
                保存草稿
              </Button>
              <Button onClick={this.previewHandle}>预览</Button>
            </>
          )}
          <Button onClick={() => this.props.history.goBack()}>返回</Button>
        </ButtonGroup>
      </div>
    );
    if (this.pageContainer) {
      footer = (
        <Affix offsetBottom={0} target={() => this.pageContainer}>
          {footer}
        </Affix>
      );
    }
    const formItems = this.getFormItems();
    return (
      <UdPage className={classNames('detail-page')}>
        {title && <UdPageHeader title={title} subTitle={subTitle} onBack={this.onBack} affixProps={{ target: () => this.pageContainer }} />}
        <Spin spinning={querying}>
          <div className="detail-body">
            <UdForm labelCol={{ span: 2 }} wrapperCol={{ span: 22 }} className="addNewAnnouncementManagementList" getForm={this.getForm} items={formItems} values={values} />
          </div>
          {footer}
        </Spin>
        {this.pageContainer && <BackTop target={() => this.pageContainer} visibilityHeight={100} />}
      </UdPage>
    );
  }

  public getAllLinkByBrandCode = (val) => {
    this.getAllClassificationList(val)
    this.getAllCustomerTypeList(val)
  }

  // 获取分类项
  public getAllClassificationList = (val) => {
    this.setState({ querying: true });
    http.get(apis.getAllClassificationList, { params: { brandCode: val } }).then((res) => {
      this.setState({ options: res.data, querying: false });
    });
  };

  // 请求获取所有客户类型发送对象
  public getAllCustomerTypeList = (val) => {
    this.setState({ querying: true });
    const dealerData = http.get(apis.SendToListOfCustomerByBrandCode, { params: { agentType: 0, isValid: 1, brandCode: val } });
    // const specialDealerData = http.get(apis.SendToListOfCustomer, { params: { agentType: 1 } });
    Promise.all([dealerData])
      .then((result) => {
        const dealerList = result[0].data.map(({ agentCode: value, agentName: title }) => ({ value, title, key: value }));
        // const specialDealerList = result[1].data.map(({ agentCode: value, agentName: title }) => ({ value, title, key: value }));

        const sendOptions = [
          {
            key: 0,
            value: 0,
            title: '经销商',
            disabled: !dealerList || !dealerList.length,
            children: dealerList,
          }/*,
          {
            key: 1,
            value: 1,
            title: '分销商',
            disabled: !specialDealerList || !specialDealerList.length,
            children: specialDealerList,
          },*/
        ];
        this.setState({ sendOptions });
      })
      .finally(() => {
        this.setState({ querying: false });
      });
  };

  // 请求获取所有产品维度类型发送对象
  public getAllProductTypeList = () => {
    this.setState({ querying: true });
    http
      .get(apis.SendToListOfProduct)
      .then((res) => {
        const data = res.data;
        const sendOptions = deepLoopFormateTree({
          datas: data,
          translate: { value: 'value', title: 'label', children: 'children', key: 'key', extra: 'sapMatCodes' },
          originKey: { value: 'id', title: 'name', children: 'children' },
        });
        this.setState({ sendOptions });
      })
      .finally(() => this.setState({ querying: false }));
    /* const sendOptions = [
      {
        value: 'product-big-class',
        label: '产品大类',
        children: [
          {
            value: 'product-mid-class',
            label: '产品中类',
            children: [
              {
                value: 'product-sm-class',
                label: '产品小类',
              },
            ],
          },
        ],
      },
      {
        value: 'jiangsu',
        label: 'Jiangsu',
        children: [
          {
            value: 'nanjing',
            label: 'Nanjing',
            children: [
              {
                value: 'xihu',
                label: 'xihu',
              },
            ],
          },
        ],
      },
    ]
    this.setState({sendOptions,querying:false}) */
  };

  // 发送对象类型改变
  public sendTypeChange = (val) => {
    this.form.setFieldsValue({ [fieldMap.sendTo]: undefined });
    this.setState({
      sendType: val,
      sendToval: [],
    });
    if (val === 0) {
      //this.getAllCustomerTypeList();
    } else if (val === 1) {
      this.getAllProductTypeList();
    }
  };

  public onBack = () => {
    this.props.history.goBack();
  };

  public getForm = (form) => {
    this.form = form;
  };

  private getFormItems = (): IUdFormItem[] =>
    this.state.sendType === 0
      ? [
          {
            id: fieldMap.brandCode,
            label: '品牌公司',
            rules: [validators.required],
            decoratorOptions: { validateFirst: true },
            render: <UdSelect showSearch options={this.brandList} onChange={this.getAllLinkByBrandCode} />,
          },
          {
            id: fieldMap.title,
            label: '标题',
            rules: [validators.required, validators.max(30), { validator: validators.noSpecialSymbol1 }],
            decoratorOptions: { validateFirst: true },
            render: <Input placeholder="请输入公告标题，最长为30个字符" />,
          },
          {
            id: fieldMap.content,
            label: '正文',
            rules: [validators.required, validators.max(CONTENT_MAX_LENGTH)],
            render: () => <EditorComponent editorState={this.state.editorState} onChange={this.handleEditorChange} editorImgUpload={this.editorImgUploadHandler} />,
          },
          {
            id: fieldMap.annex,
            label: '上传附件',
            extra: '支持扩展名：.rar  .zip  .doc  .docx  .xls  .xlsx  .pdf  .jpg  .png',
            render: () => (
              <Upload beforeUpload={this.annexFileUpload} fileList={this.state.annexFile} onRemove={this.annexFileRemove}>
                {!this.state.annexFile || !this.state.annexFile.length ? (
                  <Button>
                    <Icon type="upload" /> 上传
                  </Button>
                ) : null}
              </Upload>
            ),
          },
          { id: fieldMap.classification, label: '选择分类', rules: [validators.required], render: <ChooseClassCm options={this.state.options} addClassification={this.addClassification} /> },
          { id: fieldMap.sendType, label: '对象维度', rules: [validators.required], render: <RadioGroupCm sendTypeChange={this.sendTypeChange} /> },
          {
            id: fieldMap.sendTo,
            label: '发送对象',
            rules: [validators.required],
            render: () => {
              return (
                <TreeSelect
                  getPopupContainer={(triggerNode) => triggerNode.parentElement}
                  treeData={this.state.sendOptions}
                  // value={this.state.value}
                  // onChange={this.onChange}
                  labelInValue
                  treeCheckable={true}
                  // showCheckedStrategy={TreeSelect.SHOW_PARENT}
                  // searchPlaceholder='请选择发送对象'
                />
              );
            },
          },
        ]
      : [
          {
            id: fieldMap.title,
            label: '标题',
            rules: [validators.required, validators.max(10)],
            decoratorOptions: { validateFirst: true },
            render: <Input placeholder="请输入公告标题，最长为10个字符" />,
          },
          {
            id: fieldMap.content,
            label: '正文',
            rules: [validators.required, validators.max(CONTENT_MAX_LENGTH)],
            render: () => <EditorComponent editorState={this.state.editorState} onChange={this.handleEditorChange} editorImgUpload={this.editorImgUploadHandler} />,
          },
          {
            id: fieldMap.annex,
            label: '上传附件',
            extra: '支持扩展名：.rar  .zip  .doc  .docx  .xls  .xlsx  .pdf  .jpg  .png',
            render: () => (
              <Upload beforeUpload={this.annexFileUpload} fileList={this.state.annexFile} onRemove={this.annexFileRemove}>
                {!this.state.annexFile || !this.state.annexFile.length ? (
                  <Button>
                    <Icon type="upload" /> 上传
                  </Button>
                ) : null}
              </Upload>
            ),
          },
          { id: fieldMap.classification, label: '选择分类', rules: [validators.required], render: <ChooseClassCm options={this.state.options} addClassification={this.addClassification} /> },
          { id: fieldMap.sendType, label: '对象维度', rules: [validators.required], render: <RadioGroupCm sendTypeChange={this.sendTypeChange} /> },
          {
            id: 'productsType',
            label: '产品类别',
            rules: [validators.required],
            render: (
              <CascaderSelect
                initValue={this.state.detailData?.productsType}
                onChange={(val) => {
                  this.changeProductsType(val);
                }}
                options={this.state.sendOptions}
              />
            ),
          },
          {
            id: fieldMap.sendTo,
            label: '发送对象',
            render: (
              <div className="send-to-val-box">
                {this.state.sendToval.map((item, index) => (
                  <span key={index}>{item.agentName}</span>
                ))}
              </div>
            ),
          },
        ];

  //触发编辑器
  handleEditorChange = (editorState) => {
    this.setState({ editorState: editorState }, () => {
      let editorHtml = editorState.toHTML();
      editorHtml = editorHtml === '<p></p>' ? undefined : editorHtml;
      this.form.setFieldsValue({ [fieldMap.content]: editorHtml });
      this.form.validateFields([fieldMap.content]);
      // console.log(this.state.editorState.toHTML(),editorHtml)
      // console.log(editorHtml)
    });
  };

  //新建分类
  addClassification = () => {
    UdModal.open({
      title: '新增公告分类',
      content: (
        <UdModalForm
          items={[
            {
              id: fieldMap.brandCode,
              label: '品牌公司',
              render: <UdSelect showSearch options={this.brandList} />,
              rules: [validators.required, validators.max(10)],
            },
            {
              id: fieldMap.addClassificationName,
              label: '分类名称',
              render: <Input placeholder="请输入分类名称，最长为10个字符" />,
              rules: [validators.required, validators.max(10)],
            },
          ]}
        />
      ),
      onOk: (value) => {
        return http.post(apis.postAddClassification, value).then((res) => {
          message.success('新增成功');
          this.getAllClassificationList(value.brandCode);
        });
      },
    });
  };

  //选择发送对象
  // onChange = value => {
  //   this.setState({ value });
  // }

  //修改产品类别
  changeProductsType = (val) => {
    let value = [...val];

    // 处理产品类别数据
    const productCode = value.pop();
    const matCodes = findTreeNodeInfo(this.state.sendOptions, productCode)?.sapMatCodes;

    const getDealerList = this.getDealerByProductType(matCodes);

    getDealerList
      .then((res) => {
        this.setState(
          {
            sendToval: res.data
              ? res.data.reduce((pre, cur) => {
                  if (pre.some((item) => item.agentCode === cur.agentCode)) {
                    return pre;
                  }
                  return [...pre, cur];
                }, [])
              : [],
          },
          () => {
            console.log(this.state.sendToval);
          }
        );
      })
      .catch((err) => {
        this.setState({
          querying: false,
          sendToval: [],
        });
      });
  };

  //提交表单 || 保存草稿
  handleSend = (status) => {
    this.form.validateFields((err, values) => {
      if (!values.text) {
        message.error('正文不能为空');
      } else if (values.text.length > CONTENT_MAX_LENGTH) {
        message.error('正文内容长度不能大于' + CONTENT_MAX_LENGTH + '（包含样式和图片）');
      }
      if (!err) {
        this.setState({ querying: true });
        const { annexFile } = this.state;
        let enclosure = values.enclosure;
        if (annexFile && annexFile[0]) {
          // 处理附件字段格式{url,name}
          const annexFileData = annexFile[0];
          enclosure = { enclosureName: annexFileData.name, url: annexFileData.url };
        }
        // 处理富文本内容
        // let editorHtml = editorState.toHTML()
        // editorHtml = editorHtml === "<p></p>"?undefined:editorHtml
        // 存在src字符无法提交服务器，处理为data-src，回显时需处理回src
        values.text = values.text.replace(/src/g, 'data-src');
        /* values.text = values.text.replace(/[<">' ]/g,(str)=>{
          return {
            '<': '&lt;',
            '"': '&quot;',
            '>': '&gt;',
            ' ': '&nbsp;',
            "'": '&#39;',
            "src": 'data-src',
          }[str]
        }) */
        // 处理发送对象数据
        const type = values[fieldMap.sendType];
        if (type === 1) {
          // 处理产品类别数据
          // const productCode = values['productsType'].slice(values['productsType'].length - 1)
          // const matCodes = findTreeNodeInfo(this.state.sendOptions, productCode)?.sapMatCodes
          values['productsType'] = values['productsType']?.join(',');
          // const getDealerList = this.getDealerByProductType(matCodes)
          // getDealerList.then(res => {
          //   const dealerList = res.data
          //   values[fieldMap.sendTo] = dealerList?.map(({ agentName, agentCode }) => ({ agentName, agentCode, type }))
          //   let params = { brandCode, status, ...values, enclosure, }
          //   this.requestSubmit(params)
          // }, err => this.setState({ querying: false }))

          values[fieldMap.sendTo] = this.state.sendToval.map((item) => ({ agentCode: item.agentCode, agentName: item.agentName, type: item?.parentCode ? '1' : '0' }));

          if (!values.enclosure) {
            delete values.enclosure;
          }

          let params = enclosure ? { status, ...values, enclosure } : { status, ...values };
          if (this.state.sendToval.length < 1) {
            message.error('该产品类别下无经销商，请重新选择产品类别！');
            this.setState({ querying: false });
          } else {
            this.requestSubmit(params);
          }
        } else {
          if (Array.isArray(values[fieldMap.sendTo])) {
            values[fieldMap.sendTo] = values[fieldMap.sendTo].map(({ label: agentName, value: agentCode }) => ({ agentName, agentCode, type }));
          }
          let params = { status, ...values, enclosure };
          this.requestSubmit(params);
        }
      }
    });
  };

  public requestSubmit = (params) => {
    const { deleteFiles } = this.state;
    /* const params = {
      //品牌商代码
      // agentCode: 123,
      //品牌代码
      brandCode,
      status,
      ...values,
      enclosure,
      // text: this.state.editorState,
      // [fieldMap.sendTo]: values[fieldMap.sendTo],
    } */
    const id = this.props.match.params.id;
    let url = apis.postAddAnnouncementManagament;
    if (id) {
      params.id = id;
      url = apis.postEditAnnouncementManagament;
    }
    http
      .post(url, params)
      .then((res) => {
        // 提交成功后，去执行删除原来的文件
        if (deleteFiles && deleteFiles.length) {
          ossHttp.deleteMulti(deleteFiles);
        }
        this.props.history.goBack();
      })
      .finally(() => this.setState({ querying: false }));
  };

  //预览
  previewHandle = () => {
    this.form.validateFields((err, values: any) => {
      if (!err) {
        const { title } = values;
        const { annexFile } = this.state;
        const nowTime = new Date();
        const sendTime = dayjs(nowTime).format('YYYY-MM-DD HH:mm:ss');
        const content = this.state.editorState.toHTML();
        UdModal.open({
          title,
          content: <ViewDetailContent sendName={sendAnnounceName} time={sendTime} annexFile={annexFile} content={content} />,
          footer: null,
        });
      }
    });
  };

  // 根据产品类别获取经销商
  public getDealerByProductType = (codes) => {
    const params = { sapMatCodes: codes };
    return http.post(apis.GetDealerListByProduct, params);
  };

  public editorImgUploadHandler = (options) => {
    console.log(options);
    const { file } = options;
    this.setState({ querying: true });
    ossHttp.put('announcement/content', file).then((result) => {
      const { url, name } = result;
      // successFn({url,name})
      this.setState({
        editorState: ContentUtils.insertMedias(this.state.editorState, [
          {
            type: 'IMAGE',
            url: url,
            alt: name,
          },
        ]),
        querying: false,
      });
    });
  };

  // 附件上传
  private annexFileUpload = (file) => {
    const isTxt = file.type === 'text/plain';
    if (isTxt) {
      message.error('不能上传txt格式文件');
      return false;
    }
    const { name: fileName, uid } = file;
    this.setState({
      annexFile: [
        {
          uid,
          name: fileName,
          status: 'uploading',
        },
      ],
    });
    ossHttp.put('announcement/annex', file).then((res) => {
      const { url } = res;
      const file = {
        uid,
        name: fileName,
        status: 'done',
        url,
      };
      this.setState({
        annexFile: [file],
      });
    });
    return false;
  };
  // 附件删除
  public annexFileRemove = (file) => {
    const { url } = file;
    const key = this.getOssFileKey(url);
    if (this.needDelete(key, url)) {
      const { deleteFiles = [] } = this.state;
      this.setState({
        deleteFiles: [...deleteFiles, key],
      });
    }
    this.setState({
      annexFile: null,
    });
    return true;
  };
  // 判断是否需要删除oss上的文件
  public needDelete = (key, url) => {
    const { deleteFiles = [], detailData } = this.state;
    if (!detailData) {
      return false;
    }
    // let oldUrl = detailData?.enclosure?.url
    if (!deleteFiles.includes(key)) {
      return true;
    }
    return false;
  };
  // 获取oss文件key
  public getOssFileKey = (url) => {
    const findIndexString = '.aliyuncs.com/';
    const index = url.indexOf(findIndexString);
    const key = url.substring(index + findIndexString.length);
    return key;
  };
}

export default AddNew;

interface IUpdateAnnouncementProps
  extends RouteComponentProps<{
    id: string;
  }> {}

interface IUpdateAnnouncementState {
  brandCode?: string;
  title?: string;
  subTitle?: string;
  querying?: boolean;
  editorState?: any;
  options?: any;
  sendOptions?: any;
  annexFile?: any;
  detailData?: any;
  deleteFiles?: string[];
  sendType?: number;
  sendToval: any[];
}

function ChooseClassCm(props) {
  const { options = [], value, onChange, addClassification } = props;
  return (
    <div className="announcement-class-item">
      <Select value={value} onChange={onChange} placeholder="请选择公告分类" getPopupContainer={(triggerNode) => triggerNode.parentElement}>
        {options.map((option, index) => (
          <Select.Option key={index} value={option[fieldMap.classificationValue]}>
            {option[fieldMap.classificationName]}
          </Select.Option>
        ))}
      </Select>
      <div className="add-classification">
        <Button type="primary" onClick={addClassification}>
          新建分类
        </Button>
      </div>
    </div>
  );
}

function RadioGroupCm(props) {
  const options = [
    { value: 0, title: '客户类型' },
    // { value: 1, title: '产品类别' }, // TODO::暂时注释产品类别维度
  ];
  const { sendTypeChange, onChange } = props;
  const chooseChange = (e) => {
    const val = e.target.value;
    onChange && onChange(val);
    sendTypeChange && sendTypeChange(val);
  };
  return <UdRadioGroup value={props.value} onChange={chooseChange} options={options} />;
}

function CascaderSelect(props) {
  let { options, onChange, initValue } = props;

  const [valueArr, setvalueArr] = useState(initValue ? initValue : []);

  // 无法获取到默认传入的value，通过initValue手动传入
  // const valueArr = value ? value : initValue

  // useEffect(() => {
  //   onChange && onChange(valueArr)
  // }, [props])
  return (
    <Cascader
      options={options}
      value={valueArr}
      onChange={(val) => {
        setvalueArr(val);
        onChange(val);
      }}
      changeOnSelect={true}
    />
  );
}
